package com.yxkj.syh.app.huarong.activities.home;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.syh.app.basic.App;
import com.syh.app.basic.base.view_model.BaseViewModel;
import com.syh.app.basic.utils.Tooast;
import com.syh.app.basic.utils.net.ApiObserver;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.yxkj.syh.app.huarong.bean.AliCityResponse;
import com.yxkj.syh.app.huarong.bean.AreaPlus;
import com.yxkj.syh.app.huarong.bean.NoticeResponse;
import com.yxkj.syh.app.huarong.bean.PagesRequest;
import com.yxkj.syh.app.huarong.bean.ReturnCarsResponse;
import com.yxkj.syh.app.huarong.data_center.model.AliCityModel;
import com.yxkj.syh.app.huarong.data_center.model.CommonModel;
import com.yxkj.syh.app.huarong.data_center.model.ReportModel;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import chihane.jdaddressselector.AddressProvider;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

/**
 * 创建者：SYH
 * 时间：2020/5/20 17:27
 * 编辑者：SYH、
 * 标签：
 * 补充说明：
 */
public class HomeVM extends BaseViewModel<FragmentEvent> {
    public HomeVM(@NonNull Application application) {
        super(application);
    }

    public ObservableField<String> ofArea = new ObservableField<>("全国");

    public MutableLiveData<ReturnCarsResponse> mldReturnCarsResponse = new MutableLiveData<>();
    public MutableLiveData<List<NoticeResponse.Record>> mldNotice = new MutableLiveData();


    public void getReturnCars(PagesRequest request) {

        ReportModel.getReportModel().homeData(request, mLifecycleProvider.bindToLifecycle(), new ApiObserver<ReturnCarsResponse>() {
            @Override
            public void onSuccess(ReturnCarsResponse response) {
                mldReturnCarsResponse.setValue(response);
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
                mldReturnCarsResponse.setValue(null);
            }
        });
    }

    public void notice(){
        PagesRequest request = new PagesRequest();
        request.setPageIndex(1);
        request.setPageSize(10);
        request.setSortFields("id_d");
        List<PagesRequest.SqlParam> sqlParams = new ArrayList<>();
        request.setQueryList(sqlParams);

        CommonModel.getCommonModel().notice(request,mLifecycleProvider.bindToLifecycle(), new ApiObserver<NoticeResponse>() {
            @Override
            public void onSuccess(NoticeResponse noticeResponse) {
                mldNotice.setValue(noticeResponse.getData().getRecords());
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
            }
        });
    }

    /**
     * 地址选择器的数据源提供者
     */
    public AddressProvider addressProvider = new AddressProvider() {
        @Override
        public void provideProvinces(AddressReceiver<Province> addressReceiver) {
            addressReceiver.send(getProvince());
        }

        @Override
        public void provideCitiesWith(int provinceId, AddressReceiver<City> addressReceiver) {
            cities(provinceId, addressReceiver);
        }

        @Override
        public void provideCountiesWith(int cityId, AddressReceiver<County> addressReceiver) {
            counties(cityId, addressReceiver);
        }

        @Override
        public void provideStreetsWith(int countyId, AddressReceiver<Street> addressReceiver) {
            addressReceiver.send(null);
        }
    };

    public List<AreaPlus> areaLevel1Pluses = new ArrayList<>();
    public List<AreaPlus> areaLevel2Pluses = new ArrayList<>();
    public List<AreaPlus> areaLevel3Pluses = new ArrayList<>();
    private List<Province> provinces = new ArrayList<>();
    private List<City> cities = new ArrayList<>();
    private List<County> counties = new ArrayList<>();

    /**
     * 读省
     *
     * @return
     */
    private List<Province> getProvince() {
        if (provinces.size() == 0) {
            try {
                // 获取json文件数据源,流的方式呈现
                InputStream inputStream = App.getApplication().getAssets().open("province.json");
                // 读取JSON文件流
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String temp = "";
                String jsonSource = "";
                //一行一行的读取
                while ((temp = bufferedReader.readLine()) != null) {
                    jsonSource += temp;
                }
                //关闭
                bufferedReader.close();
                inputStream.close();

                JSONObject jsonObject = new JSONObject(jsonSource);
                List<AreaPlus> areaPluses = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<AreaPlus>>() {
                }.getType());

                areaLevel1Pluses.clear();
                AreaPlus all = new AreaPlus();
                all.setAreaName("全部");
                areaLevel1Pluses.add(all);
                areaLevel1Pluses.addAll(areaPluses);

                for (int i = 0; i < areaLevel1Pluses.size(); i++) {
                    AreaPlus provincePlus = areaLevel1Pluses.get(i);
                    Province province = new Province();
                    province.name = provincePlus.getAreaName();
                    province.id = i + 1;
                    provinces.add(province);
                    provincePlus.setProvince(province);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return provinces;
    }

    /**
     * 查市
     */
    public void cities(int provinceId, AddressProvider.AddressReceiver<City> addressReceiver) {

        if (provinceId > 1) {
            AliCityModel.getAliCityModel().getAliCity(getAreaPlusId(1, provinceId), mLifecycleProvider.bindToLifecycle(), new ApiObserver<AliCityResponse>() {
                @Override
                public void onSuccess(AliCityResponse response) {
                    if (response.getShowapi_res_code() == 0) {
                        areaLevel2Pluses.clear();
                        AreaPlus all = new AreaPlus();
                        all.setAreaName("全部");
                        areaLevel2Pluses.add(all);
                        areaLevel2Pluses.addAll(response.getShowapi_res_body().getData());
                        cities.clear();
                        for (int i = 0; i < areaLevel2Pluses.size(); i++) {
                            AreaPlus areaPlus = areaLevel2Pluses.get(i);
                            City city = new City();
                            city.id = i + 1;
                            city.name = areaPlus.getAreaName();
                            city.province_id = provinceId;
                            areaPlus.setCity(city);
                            cities.add(city);
                        }
                        addressReceiver.send(cities);
                    }
                }

                @Override
                public void onFailed(int code, String msg) {
                    Tooast.warning(msg);
                }
            });
        } else {
            addressReceiver.send(null);
        }
    }

    /**
     * 查区县
     */
    public void counties(int cityId, AddressProvider.AddressReceiver<County> addressReceiver) {
        if (cityId > 1) {
            AliCityModel.getAliCityModel().getAliCity(getAreaPlusId(2, cityId), mLifecycleProvider.bindToLifecycle(), new ApiObserver<AliCityResponse>() {
                @Override
                public void onSuccess(AliCityResponse response) {
                    if (response.getShowapi_res_code() == 0) {
                        areaLevel3Pluses.clear();
                        AreaPlus all = new AreaPlus();
                        all.setAreaName("全部");
                        areaLevel3Pluses.add(all);
                        areaLevel3Pluses.addAll(response.getShowapi_res_body().getData());
                        counties.clear();
                        for (int i = 0; i < areaLevel3Pluses.size(); i++) {
                            AreaPlus areaPlus = areaLevel3Pluses.get(i);
                            County county = new County();
                            county.id = i + 1;
                            county.name = areaPlus.getAreaName();
                            county.city_id = cityId;
                            areaPlus.setCounty(county);
                            counties.add(county);
                        }
                        addressReceiver.send(counties);
                    }
                }

                @Override
                public void onFailed(int code, String msg) {
                    Tooast.warning(msg);
                }
            });
        } else {
            addressReceiver.send(null);
        }
    }

    /**
     * 查 AreaPlusId
     *
     * @param subId      子类 id
     */
    public long getAreaPlusId(int level, int subId) {
        long id = 0l;

        if (level == 1) {
            for (AreaPlus areaPlus : areaLevel1Pluses) {
                if (areaPlus.getProvince().id == subId) {
                    id = Long.decode(areaPlus.getId());
                    break;
                }
            }
        } else if (level == 2) {
            for (AreaPlus areaPlus : areaLevel2Pluses) {
                if (areaPlus.getCity().id == subId) {
                    id = Long.decode(areaPlus.getId());
                    break;
                }
            }
        }else if (level==3){
            for (AreaPlus areaPlus : areaLevel3Pluses) {
                if (areaPlus.getCounty().id == subId) {
                    id = Long.decode(areaPlus.getId());
                    break;
                }
            }
        }


        return id;
    }

}
